package servlet;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.UserInfoDao;
import entity.UserInfo;

/**
 * Servlet implementation class registerdervlet
 */
@WebServlet("/registerdervlet")
public class registerdervlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public registerdervlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        UserInfo userInfo = new UserInfo();
        UserInfoDao userInfoDao = new UserInfoDao();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");

        try {
            int flag = userInfoDao.registerNewUser(username, password, email, gender);
            if (flag == 1) {
                // 注册成功，重定向到首页
                response.sendRedirect("index.jsp");
            } else {
                // 注册失败，设置错误信息并转发到注册页面
                request.setAttribute("errorMsg", "用户名已存在，请重新输入！");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            // 数据库异常，设置错误信息并转发到注册页面
            request.setAttribute("errorMsg", "注册失败，请稍后重试！");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
